var express = require('express');
var azure = require('azure');
var request = require('request');

// https://jaxevents.blob.core.windows.net/
var azureaccountName = "jaxevents";
var azureaccountKey = "g3wkbVtnb1vG2XojdbXayqnQ5bhvlO2svfdTmYQteKkT9UMkQNDco4rJmzs/CCJS49vIzel8+FF14FZlF4Ur0w==";
var eventfulKey = "7mxCcWH78VJRw4Hv";

var app = express();

// Example request: http://localhost/eventful/rest/events/search?location=jacksonville&sort_order=popularity
// http://api.eventful.com/rest/events/search?location=jacksonville&sort_order=popularity
var apiUrl = "http://api.eventful.com/";

app.use('/eventful', function(req, res) {
	var url = apiUrl + req.url + "&app_key=" + eventfulKey;
	req.pipe(request(url)).pipe(res);
});

app.use('/cache', function(req, res) {
	var blobname = req.query.blobname;
	var url = apiUrl + req.url + "&app_key=" + eventfulKey;
	res.send("success");
	request.get(url, function(err, response, body) {
		if (err) {
			console.log('Unable to connect.' + err);
		} else if (response.statusCode !== 200) {
			console.log('response=' + response.statusCode);
		} else {
			save(body, blobname);
		}
	});
});

function save(body, blobname) {
	var containerName = 'events';
	var blobService = azure.createBlobService(azureaccountName, azureaccountKey);
	blobService.createContainerIfNotExists(containerName
	    , { publicAccessLevel: 'blob' }
		, function(error) {
    		if (!error) {
    			blobService.createBlockBlobFromText(containerName, blobname, body, { contentEncoding: 'UTF-8', contentType: 'application/json' }, function(error) {
    				if (!error) {
    					// File has been uploaded
    				}
    			});
    		} else {
    			console.log(error);
    		}
		}
	);
}

app.listen(process.env.port || 80);